<?php

/*
  FileTransfer File for Incoming Transactions
 */
$__sysBanks = getBankList();
$__sysCountries = getCountryList();
$__sysCities = getCityList($__sys['Country']);
$__sysAgencies = getAgencyList();
$__sysDomains = getDomainList();
$__sysRcvAcountType = getAccountList();
$__sysCurrency = getCurrencyList();
$__sysPaymentMode = getPaymentModeList();

$FileList = IncomeTransact_LoadFile($GETCOMMETH[1]['tcmtChannel'], $GetSettings[1]['set_Valor'], $CORRESP_FTDIR, $PID, $PrefixIndex[$PID]);
$nFiles = count($FileList);
for ($p = 0; $p < $nFiles; $p++) {

    $TransmissionResultCode = 0;
    if ($handle = fopen($GetSettings[1]['set_Valor'] . "/" . $CORRESP_FTDIR . "/IN/" . $FileList[$p], "r")) {

        #Pre-set Vars
        $SUMTransactionA = 0;
        $SUMTransactionB = 0;
        $ftdata = 'INSERT INTO facturas
				(FraOrdenPago,FraFechaIngreso,FraOrigen0,FraEnviado,FraCambio,FraARecibir,FraMonDPago,FraMensaje,FraModoPago,FraAgenciaPago,FraNotas,FraClave,FraStatus,FraModo) VALUES ';
        $ftdata_extend = 'INSERT INTO facturasextjoins
				(FraExtID,FraCliNombre,FraCliDNI,FraBnfNombre,FraBnfCedula,FraBnfDireccion,FraBnfBarrio,FraBnfCiudad,FraBnfTelefono,FraBnfPais,FraBancoID,FraSucursal,FraTipoCuenta,FraCuenta,FraClPais,FraCliDomicilio,FraCliCP,FraCliTelefono,FraCliTelefono2,FraCliCiudad) VALUES ';
        $ftdata_income = 'INSERT INTO facturas_income
				(FraIncID,FraIncCorresponsal,FraIncOrdenPago,FraIncOrdenTrans,FraIncFechaCo,FraIncReferenciaCo,FraIncComisionCo,FraIncVersion) VALUES ';
        
        $BankCheck = '';
        CONN('MYT');
        $FILESEP = array('', ',', ';', '	', '|');
        #Clear Vars
        unset($fileprp);
        unset($iDsearch);
        unset($iDreplace);

        $row = 0;

        #	Valida
        $CorrProperties = $GLOBALS['MYT']->db_array("SELECT CorrNumero, CorrFormatoFichero, CorrAlias FROM corresponsales WHERE CorrAgente = '{$GETCOMMETH[1]['CorrAgente']}'");
        $fileprp = transaction_filenamereturn($FileList[$p], $GetMethodParams[1]['ffFilenameFormat']);

        if ($fileprp[0] == 'err') {
            $error = $fileprp[1];
        } else {
            $CorrTransaction = $fileprp[1];
            $ReceivedDate = $fileprp[2];
            $ReceivedTime = $fileprp[3];
        }
        if (!isset($CorrProperties[1]) || isset($error)) {
            #Gerar alerta, Recebida transaccao de correspondente inexiste ou com configuracao incorrecta
            $error = "Invalid transaction";
        } else {

            # Inicia tratamento de transaccao, captados valores do nome do ficheiro
            if ($CorrProperties[1]['CorrFormatoFichero'] == 7) {
                
            }
            # Verifica repeticoes de lote
            $CorrExpectedTransaction = $GLOBALS['MYT']->db_array("SELECT Trs_CorrTrans FROM transmitions WHERE Trs_Corr = {$CorrProperties[1]['CorrNumero']} AND Trs_CorrTrans = {$CorrTransaction} AND Trs_Modo = 2");

            if ($CorrTransaction < 1 || isset($CorrExpectedTransaction[1])) { # Alterado de igual para menor por ser possivel haver saltos na numeracao
                $error = 'O numero de transaccao nao é valida.';
            } else {
                //#Verificacao de Ordem
                #Verificacao de Data
                #if($FILESEP[$GetMethodParams[1]['DELIMITER']]==''){$data = fgets($handle,2048);}else{$data = fgetcsv($handle,2048,$FILESEP[$GetMethodParams[1]['DELIMITER']]);}
                $TransactionModel = $TFTPATH_MODELS.$GetMethodParams[1]['DELIMITER'] . '_' . $GetMethodParams[1]['EXT'] . '_' . $GetMethodParams[1]['OB'] . '_' . $GetMethodParams[1]['VERSION'] . '_' . $PID . '.php';

                if ($GetMethodParams[1]['EXT'] != 'xml') {
                    while (($data = fgetcsv($handle, 2048, ';')) !== FALSE) {
                        include($TransactionModel);
                    }
                } else {
                    $data_contents = xml_getparse(file_get_contents($GetSettings[1]['set_Valor'] . "/" . $CORRESP_FTDIR . "/IN/" . $FileList[$p], true));
                    $data_count = count($data_contents);
                    while ($row < $data_count) {
                        $data = $data_contents['Transaction'];
                        include($TransactionModel);
                    }
                }
                fclose($handle);
                if ($row > 0) {
                    #Regista Lote
                    $dbRow = tuga_multiquery("CALL transact_receiveorder ($CorrTransaction,{$CorrProperties[1]['CorrNumero']},0,'{$sysTime}',{$row},{$SUMTransactionA},{$SUMTransactionB}, @OpID, @TransactionID,@TransmissionID,@TransmissionFlag); SELECT @OpID, @TransactionID,@TransmissionID,@TransmissionFlag;");
                    $dbRow = $dbRow[0];
                    #Verifica se transaccao � valida
                    if ($dbRow[3] > 0) {
                        #Salva Ficheiro do Lote
                        if ($GLOBALS['MYT']->db_query(str_replace('&#TransactOrder#&', $dbRow[0], substr($ftdata, 0, strlen($ftdata) - 1))) == true) {

                            if ($GET = $GLOBALS['MYT']->db_array("SELECT FraID FROM facturas WHERE FraOrdenPago = " . $dbRow[0] . " AND FraModo = 2 ORDER BY FraID")) {
                                for ($i = 1; $i <= $GET[0]; $i++) {
                                    $iDsearch[] = '&#ExtendedID' . $i . '#&';
                                    $iDreplace[] = $GET[$i]['FraID'];
                                }
                                $Msg_CONF = 1;
                                $GLOBALS['MYT']->db_query(str_replace($iDsearch, $iDreplace, substr($ftdata_extend, 0, strlen($ftdata_extend) - 1)));
                                $GLOBALS['MYT']->db_query(str_replace('&#TransactOrder#&', $dbRow[0], str_replace('&#TransactTrans#&', $dbRow[2], str_replace($iDsearch, $iDreplace, substr($ftdata_income, 0, strlen($ftdata_income) - 1)))));
                                $GLOBALS['MYT']->db_query("UPDATE facturas SET FraOrdenPago = 0 WHERE FraOrdenPago = " . $dbRow[0] . " AND FraModo = 2");
                                $GLOBALS['MYT']->db_query("UPDATE ordenespago SET Op_Enviada = 0 WHERE Op_Orden = " . $dbRow[0]);
                                $GLOBALS['MYT']->db_query("UPDATE transmitions SET TrsDate = '$ReceivedDate $ReceivedTime' WHERE Trs_ID = " . $dbRow[2]);
                            }
                        }
                        $TransmissionResultCode = 2;
                    } else {
                        $TransmissionResultCode = 5;
                    }
                } else {
                    $error = 'Nothing to import';
                }
            }
        }
        if (isset($error)) {
            $Msg_ERROR = $error;
        }
        IncomeTransact_StoreFile($TransmissionResultCode, $GetSettings[1]['set_Valor'], $CORRESP_FTDIR, $FileList[$p], $GLOBALS['DOC']);
    } else {
        echo "erro a ler o ficheiro.";
    }
}
?>